package com.zr.redis.configuration;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RedissonConfig {

    @Value("${spring.redis.host:localhost}")
    private String host;

    @Value("${spring.redis.port:6379}")
    private int port;

    @Value("${spring.redis.password:}")
    private String password;

    // 自定义看门狗参数
    @Value("${redisson.lock.watchdog.timeout:30000}") // 默认30秒
    private long watchdogTimeout;

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        // 单节点模式
        String address = "redis://" + host + ":" + port;
        config.setLockWatchdogTimeout(watchdogTimeout);
        config.useSingleServer()
                .setAddress(address)
                .setPassword(password.isEmpty() ? null : password)
                .setDatabase(0); // 默认数据库

        // 如果是集群模式，可以使用下面的配置
        // config.useClusterServers()
        //         .addNodeAddress("redis://127.0.0.1:7001", "redis://127.0.0.1:7002")
        //         .setPassword(password);

        return Redisson.create(config);
    }
}

